﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using WebPartBase;

using System.Web.UI.HtmlControls;

namespace ImageSlider.ImageSlider
{
    [ToolboxItemAttribute(false)]
    public class ImageSlider : WebPart
    {
        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared)]
        public string ListName { get; set; }

        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared)]
        public int PanelHeight { get; set; }

        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared)]
        public int PanelWidth { get; set; }

        protected override void CreateChildControls()
        {
            try
            {
                //Panel creation
                Panel photos = new Panel();
                photos.ID = Constants.photosIDValue;
                photos.CssClass = Constants.photosClassValue;
                this.Controls.Add(photos);
                Panel panel, overLay;
                Image img;
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (!string.IsNullOrEmpty(this.ListName))
                        {

                            var listName = web.Lists.TryGetList(this.ListName.ToString());
                            if (listName != null)
                            {

                                SPList list = web.Lists[listName.ToString()];
                                //Getting the latest folder in the list
                                string serverPath = web.Url.ToString();
                                //Check if list has folders
                                if (list.Folders.Count != 0)
                                {
                                    SPQuery query = new SPQuery();
                                    query.Query = Constants.queryPicLib;
                                    query.RowLimit = 1;
                                    SPListItemCollection itemColl = list.GetItems(query);
                                    //check if list has folders has items
                                    if (itemColl.Count > 0)
                                    {
                                        SPFolder rootFolder = itemColl[0].Folder;
                                        SPFileCollection images = rootFolder.Files;
                                        //traverse the images and get the items
                                        foreach (SPFile image in images)
                                        {

                                            panel = new Panel();
                                            panel.CssClass = Constants.panelClassValue;
                                            img = new Image();
                                            img.ImageUrl = serverPath + "/" + image.Url.ToString();
                                            panel.Controls.Add(img);
                                            if (PanelHeight > 0)
                                            {
                                                panel.Height = PanelHeight;
                                            }
                                            if (PanelWidth > 0)
                                            {
                                                panel.Width = PanelWidth;
                                            }
                                            //Panel
                                            overLay = new Panel();
                                            panel.Controls.Add(overLay);
                                            photos.Controls.Add(panel);

                                        }

                                        //Make Iframe
                                        HtmlGenericControl ul = new HtmlGenericControl(Constants.HTMLControlValue);
                                        ul.Attributes.Add(Constants.HTMLControlClassName, Constants.HTMLControlClassValue);
                                        photos.Controls.Add(ul);
                                        HtmlGenericControl li;
                                        //foreach (SPListItem item in itemColl)
                                        //{
                                        foreach (SPFile image in images)
                                        {
                                            li = new HtmlGenericControl(Constants.HTMLImageControlValue);
                                            img = new Image();
                                            //img.ImageUrl = serverpath + item.File.Url.ToString();
                                            img.ImageUrl = serverPath + "/" + image.Url.ToString();
                                            li.Controls.Add(img);
                                            ul.Controls.Add(li);
                                        }
                                    }
                                    else
                                    {
                                        UserFriendly("No folders found in the specified library");
                                    }
                                }
                                else
                                {
                                    UserFriendly("There are no items in the folder");
                                }
                            }
                            else
                            {
                                // Create the list and columns if it does not exists
                                web.Lists.Add(this.ListName.ToString(), "List to Upload images", SPListTemplateType.PictureLibrary);
                                SPList list = web.Lists[this.ListName.ToString()];
                                UserFriendly(list + " was created since it was not available please upload images into the pic library");

                            }
                        }
                        else
                        {
                            UserFriendly("Please enter a list name using webpart properties");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UserFriendly("Exception occured during loading of images, Please contact Admin");
                Helper.LogtoList("Exception occured during loading of images, Please contact Admin", Helper.LogSeverity.Error, ex.StackTrace, ex.Message);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            //RegisterScriptAndCSS();
        }



        public void UserFriendly(string userFriendlyMessage)
        {

            Controls.Add(new Label() { Text = userFriendlyMessage });
        }
        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                StringBuilder js = new StringBuilder();

                js.AppendLine("var head = document.getElementsByTagName(\"head\")[0];");
                js.AppendLine("if(document.createStyleSheet)");
                js.AppendLine("{");
                js.AppendLine(" document.createStyleSheet('" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/css/album.css" + "');");
                js.AppendLine("} else {");
                js.AppendLine(" var css = document.createElement('link');");
                js.AppendLine(" css.type = 'text/css';");
                js.AppendLine(" css.rel = 'stylesheet';");
                js.AppendLine(" css.href = '" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/css/album.css" + "';");
                js.AppendLine(" head.appendChild(css);");
                js.AppendLine("}");
                writer.WriteLine("<script type=\"text/javascript\" src=\"" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/jquery.js\"></script>");
                writer.WriteLine("<script type=\"text/javascript\" src=\"" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/script/Jgalleryview.js\"></script>");
                writer.WriteLine("<script type=\"text/javascript\" src=\"" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/script/Jtimers.js\"></script>");
                writer.WriteLine("<script type=\"text/javascript\">");
                writer.WriteLine("$(document).ready(function() {");
                writer.WriteLine(" $('.galleryview').galleryView({");
                if (PanelWidth < 1)
                {
                    writer.WriteLine("     panel_width: 800,");
                }
                if (PanelHeight < 1)
                {
                    writer.WriteLine("     panel_height: 300,");
                }
                writer.WriteLine("     frame_width: 100,");
                writer.WriteLine("     frame_height: 100,");
                writer.WriteLine("     img_path: '" + SPContext.Current.Site.Url + "/Style%20Library/ImageSlider/Images'");
                writer.WriteLine(" });");
                writer.WriteLine("});");
                writer.WriteLine("</script>");
                base.RenderContents(writer);
                writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
                writer.RenderBeginTag(HtmlTextWriterTag.Script);
                writer.WriteLine(js.ToString());
                writer.RenderEndTag();

            }
            catch (Exception ex)
            {
                UserFriendly("Exception occured during loading of images, Please contact Admin");
                Helper.LogtoList("Exception occured during loading of images, Please contact Admin", Helper.LogSeverity.Error, ex.StackTrace, ex.Message);

            }
        }
    }
}
